﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Crowler.Model.CoreComponents;

namespace CoreComponents
{
    public class WcfServiceWrapper<T> : IDisposable, IWcfServiceWrapper<T> where T : class
    {
        ChannelFactory<T> _factory;
        private T _channel;

        private readonly Binding _binding;
        private readonly EndpointAddress _endPoint;

        private readonly object _lockObject = new object();

        public WcfServiceWrapper(Binding binding,EndpointAddress endPoint)
        {
            _endPoint = endPoint;
            _binding = binding;
        }

        public T Channel
        {
            get
            {
                lock (_lockObject)
                {
                    if (_factory == null || _factory.State!= CommunicationState.Opened )
                    {
                        _factory = new ChannelFactory<T>(_binding, _endPoint);
                   
                    }
                    _channel = _factory.CreateChannel();
                }
                return _channel;
            }
        }

        public void Dispose()
        {
            DisposeChannelFactory();
            GC.SuppressFinalize(this);
        }


        public void DisposeChannelFactory()
        {
            if (_channel != null)
            {
                ((IClientChannel)_channel).Close();
            }
            if (_factory != null)
            {
                _factory.Close();
            }
        }
    }
}